package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.homeservicemanagementsystem.entity.*;
import com.heima.homeservicemanagementsystem.entity.dto.Option;
import com.heima.homeservicemanagementsystem.mapper.EmployeesMapper;
import com.heima.homeservicemanagementsystem.service.EmployeesAndServiceService;
import com.heima.homeservicemanagementsystem.service.ServiceClassificationService;
import com.heima.homeservicemanagementsystem.utils.PasswordUtils;
import com.heima.homeservicemanagementsystem.utils.RedisClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.heima.homeservicemanagementsystem.module.PageParams;
import com.heima.homeservicemanagementsystem.module.Result;
import jakarta.annotation.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.heima.homeservicemanagementsystem.service.EmployeesService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.dev33.satoken.SaManager.log;

/**
 * 从业人员;(employees)表控制层
 *
 * @author : http://www.chiner.pro
 * @date : 2025-4-22
 */
@Tag(name = "从业人员对象功能接口")
@RestController
@RequestMapping("/employees")
public class EmployeesController {

    @Resource
    private EmployeesService employeesService;
    @Resource
    private EmployeesMapper employeesMapper;
    @Resource
    private RedisClient redisClient;
    @Resource
    private EmployeesAndServiceService employeesAndServiceService;
    @Operation(summary = "分页查询")
    @PostMapping("/page")
    public Result<Page<Employees>> paginQuery(@RequestBody PageParams<Employees> pageParams) {
        //查询参数
        Employees params = pageParams.getParams();
        LambdaQueryWrapper<Employees> lqw = new LambdaQueryWrapper<>();


        lqw.eq(params.getPhone() != null, Employees::getPhone, params.getPhone());


        lqw.eq(params.getPassword() != null, Employees::getPassword, params.getPassword());

        return Result.success(employeesService.page(pageParams.getPage(), lqw));
    }

    @SaIgnore
    @Operation(summary = "服务人员下拉列表")
    @GetMapping("/serviceChild")
    public Result<List<Option>> roleOptionschildren() {
        //查询参数

        QueryWrapper<Employees> lqw = new QueryWrapper<>();
        lqw.select("phone AS label", "id AS value");
//        lqw.eq("type", 1);
        List<Map<String, Object>> maps = employeesService.listMaps(lqw);

        List<Option> optionals = BeanUtil.copyToList(maps, Option.class);
        return Result.success(optionals);
    }

    @Operation(summary = "从业人员所有搜索")
    @GetMapping("/list")
    public Result searchQuery() {
        return Result.success(employeesService.list());
    }

    @Operation(summary = "有条件的搜索")
    @PostMapping("/tjSearch")
    public Result Query(@RequestBody Employees employees) {
        LambdaQueryWrapper<Employees> lqw = new LambdaQueryWrapper<>();


        lqw.eq(employees.getId() != null, Employees::getId, employees.getId());


        lqw.eq(employees.getPhone() != null, Employees::getPhone, employees.getPhone());


//        lqw.eq(employees.getPassword() != null, Employees::getPassword, employees.getPassword());


        return Result.success(employeesService.list(lqw));
    }

    /**
     * 新增数据
     *
     * @param employees 实例对象
     * @return 实例对象
     */
    @SaIgnore
    @Operation(summary = "注册数据")
    @PostMapping("/insert")
    public Result<Boolean> insert(@RequestBody Employees employees) {
        String key = "mobileCode-" + employees.getPhone();
        String s = redisClient.get(key);
//            log.info("验证码：{}", login.getCaptcha());
        boolean equals = employees.getCode().equals(s);
//            log.info("相等+：{}", equals);
//            log.info("相等-：{}", StringUtils.hasLength(login.getCaptcha()));
        if (!StringUtils.hasLength(employees.getCode()) || !equals) {
            return Result.error(500, "验证码错误,请重新获取");
        } else {
            log.info("前端信息：{}", employees);
            QueryWrapper<Employees> wrapper = new QueryWrapper<>();
            wrapper.eq(StringUtils.hasLength(employees.getPhone()), "phone", employees.getPhone());
            boolean exists = employeesService.exists(wrapper);
            if (exists) {
                return Result.error(500, "该手机号已被注册");
            }
            String salt = RandomUtil.randomString(16);
            employees.setSlat(salt);
            String encryptedPassword = PasswordUtils.encrypt(salt, employees.getPassword());
            employees.setPassword(encryptedPassword);

            employeesService.save(employees);
            return Result.success();

        }
    }

    @SaIgnore
    @Operation(summary = "后台注册数据")
    @PostMapping("/htinsert")
    public Result<Boolean> htinsert(@RequestBody Employees employees) {

        log.info("前端信息：{}", employees);
        QueryWrapper<Employees> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(employees.getPhone()), "phone", employees.getPhone());
        boolean exists = employeesService.exists(wrapper);
        if (exists) {
            return Result.error(500, "该手机号已被注册");
        }
        String salt = RandomUtil.randomString(16);
        employees.setSlat(salt);
        String encryptedPassword = PasswordUtils.encrypt(salt, employees.getPassword());
        employees.setPassword(encryptedPassword);

        employeesService.save(employees);
        return Result.success();


    }

    @SaIgnore
    @Operation(summary = "登录")
    @PostMapping("modileLogin")
    public Result<Map<String, String>> modileLogin(@RequestBody Employees employees) {
        Employees user = employeesService.getOne(Wrappers.<Employees>lambdaQuery().eq(Employees::getPhone, employees.getPhone()));
        if (user == null) {
            return Result.error("账号或者密码错误");
        }
        log.info("获取的用户信息：{}", user);
        String password = employees.getPassword();
        String salt = user.getSlat();
        String s = PasswordUtils.decryptStr(salt, user.getPassword());
        log.info("登录密码：{}，数据库密码：{}", password, s);
        if (password.equals(s)) {
            StpUtil.login(user.getId(), "mobile");
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            Map<String, String> map = new HashMap<>(2);
            map.put("tokenHead", tokenInfo.tokenName);
            map.put("token", tokenInfo.tokenValue);
            return Result.success(map);
        }
        return Result.error();
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/wxUsersearch")
    public Result getwxUser() {

//        LambdaQueryWrapper<WxUser> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(WxUser::getOpenid, wxUser.getOpenid());
//        lqw.eq(WxUser::getId, wxUser.getId());

        Employees byId = employeesService.getById(StpUtil.getLoginIdAsString());
        byId.setPassword(null);
        byId.setSlat(null);
        return Result.success(byId);
    }

    @SaIgnore
    @GetMapping("logout")
    @Operation(summary = "退出登录")
    public Result<Boolean> logout() {
        StpUtil.logout();
        return Result.success();
    }

    /**
     * 更新数据
     *
     * @param employees 实例对象
     * @return 实例对象
     */
    @SaIgnore
    @Operation(summary = "更新数据")
    @PutMapping("update")
    public Result update(@RequestBody Employees employees) {
        Employees user = employeesService.getOne(Wrappers.<Employees>lambdaQuery().eq(Employees::getPhone, employees.getPhone()));
        if (user == null) {
            return Result.error("账号不存在");
        }
        String key = "mobileCode-" + employees.getPhone();
        String s = redisClient.get(key);
//            log.info("验证码：{}", login.getCaptcha());
        boolean equals = employees.getCode().equals(s);
//            log.info("相等+：{}", equals);
//            log.info("相等-：{}", StringUtils.hasLength(login.getCaptcha()));
        if (!StringUtils.hasLength(employees.getCode()) || !equals) {
            return Result.error(500, "验证码错误,请重新获取");
        } else {
            LambdaUpdateWrapper<Employees> lambdaUpdateWrapper = new UpdateWrapper<Employees>().lambda();
            Employees sysUser = new Employees();
            String salt = RandomUtil.randomString(16);
            sysUser.setSlat(salt);
            String encryptedPassword = PasswordUtils.encrypt(salt, employees.getPassword());
            sysUser.setPassword(encryptedPassword);

            lambdaUpdateWrapper.set(sysUser.getPassword() != null, Employees::getPassword, sysUser.getPassword())
                    .set(sysUser.getSlat() != null, Employees::getSlat, sysUser.getSlat());

            if (employeesMapper.update(null, lambdaUpdateWrapper) > 0) {
                return Result.success("修改成功");
            }
            return Result.error("修改失败");
        }


    }

    @SaIgnore
    @Operation(summary = "更新数据")
    @PutMapping("htupdate")
    public Result gtupdate(@RequestBody Employees employees) {
        Employees user = employeesService.getOne(Wrappers.<Employees>lambdaQuery().eq(Employees::getPhone, employees.getPhone()));
        if (user == null) {
            return Result.error("账号不存在");
        }

        LambdaUpdateWrapper<Employees> lambdaUpdateWrapper = new UpdateWrapper<Employees>().lambda();
        Employees sysUser = new Employees();
        String salt = RandomUtil.randomString(16);
        sysUser.setSlat(salt);
        String encryptedPassword = PasswordUtils.encrypt(salt, employees.getPassword());
        sysUser.setPassword(encryptedPassword);

        lambdaUpdateWrapper.set(sysUser.getPassword() != null, Employees::getPassword, sysUser.getPassword())
                .set(sysUser.getSlat() != null, Employees::getSlat, sysUser.getSlat());

        if (employeesMapper.update(null, lambdaUpdateWrapper) > 0) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");


    }

    /**
     * 通过主键删除数据
     *
     * @param undefinedId 主键
     * @return 是否成功
     */
    @Operation(summary = "通过主键删除数据",
            parameters = {
                    @Parameter(name = "undefinedId", description = "主键", required = true, in = ParameterIn.PATH)
            })
    @DeleteMapping("/delete/{undefinedId}")
    public Result<Boolean> deleteById(@PathVariable String undefinedId) {

        if (employeesService.removeById(undefinedId)) {
            return Result.success();
        }
        return Result.error();
    }

    @Operation(summary = "多id删除数据")
    @DeleteMapping("/delete")
    public Result<Boolean> deleteByIds(@RequestBody List<String> id) {
        log.info("前端信息：{}", id);
        if (employeesService.removeByIds(id)) {
            employeesAndServiceService.remove(new QueryWrapper<EmployeesAndService>().eq("user_id",id));
            return Result.success();
        }
        return Result.error();
    }
}